package com.ynsj.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

@Configuration
@EnableConfigurationProperties(value = {IdProperties.class})
public class IdAutoConfiguration {

    private static IdProperties idProperties;

    private static RestTemplate restTemplate = new RestTemplate();

    public IdAutoConfiguration(IdProperties idProperties){
         IdAutoConfiguration.idProperties = idProperties;
    }

    /**
     * 用户信息实名认证
     * @param realName 用户的真实姓名
     * @param cardNum 用户的身份证号
     * @return 验证的结果
     */
    public static boolean check(String realName,String cardNum){
        /**
         * 本次我们使用AppCode的形式验证
         *  -H 'Authorization:APPCODE 你自己的AppCode'
         */
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Authorization","APPCODE "+idProperties.getAppCode());
        String format = String.format(
                idProperties.getUrl(), cardNum, realName);
        ResponseEntity<String> responseEntity = restTemplate.exchange(String.format(
                        idProperties.getUrl(), cardNum, realName),
                HttpMethod.GET,
                new HttpEntity<>(null, httpHeaders),
                String.class);
        if (responseEntity.getStatusCode() == HttpStatus.OK){
            String body = responseEntity.getBody();
            JSONObject jsonObject = JSON.parseObject(body);
            String status = jsonObject.getString("status");
            //验证成功
            return "01".equals(status);
        }
        return false;
    }
}
